package com.jic.order.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.PageResult;
import com.jic.common.utils.DateUtils;
import com.jic.common.utils.IDUtils;
import com.jic.order.entity.*;
import com.jic.order.exception.AppRuntimeException;
import com.jic.order.manage.request.OrderBaleRequest;
import com.jic.order.manage.response.OrderBaleResponse;
import com.jic.order.mapper.*;
import com.jic.order.request.OrderDeliverQueryPage;
import com.jic.order.rest.request.OrderBaleRestRequest;
import com.jic.order.rest.response.OrderBaleDeliveryResponse;
import com.jic.order.rest.response.OrderBaleInfoResponse;
import com.jic.order.service.OrderBaleDeliveryService;
import com.jic.order.service.OrderBaleService;
import com.jic.order.utils.BeanUtil;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.jic.order.utils.SerialNoUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 包裹表
 *
 * @author : yinhaijun
 * @version : v1.0.0
 * @email :
 * @since : 2020-01-15 07:06:30
 */
@Service
public class OrderBaleServiceImpl implements OrderBaleService {

	@Autowired
	private OrderBaleMapper orderBaleMapper;
	@Autowired
	private OrderBaleDeliveryMapper orderBaleDeliveryMapper;
	@Autowired
	private OrderDeliverMapper orderDeliverMapper;
	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private OrderBaleDetailMapper orderBaleDetailMapper;

	@Autowired
	private OrderBaleDeliveryService orderBaleDeliveryService;

	@Override
	public long insert(OrderBaleRequest obr) {
		OrderBale orderBale = BeanUtil.copy(obr, OrderBale.class);
		return orderBaleMapper.insert(orderBale);
	}

	@Override
	public long update() {
		OrderBale orderBale = new OrderBale();
		orderBale.setOrderStatus(2);
		orderBale.setUpdateTime(new Date());
		return orderBaleMapper.update(orderBale);
	}

	@Override
	public OrderBale queryByPrimaryKey(Long id) {
		return orderBaleMapper.queryByPrimaryKey(id);
	}

	@Override
	public List<OrderBale> query(OrderBale orderBale) {
		return orderBaleMapper.query(orderBale);
	}

	@Override
	public PageResult<OrderBaleResponse> queryPage(OrderBaleRequest obr) {
		int startIndex = (obr.getStart() - 1) * obr.getLimit();
		List<OrderBaleResponse> list = orderBaleMapper.queryPage(startIndex, obr);
		long count = orderBaleMapper.queryPageCount(obr);

		PageResult<OrderBaleResponse> pageResult = new PageResult<>();
		pageResult.setRows(list);
		pageResult.setTotal(count);
		return pageResult;
	}

	@Override
	public OrderBaleInfoResponse getDeliveryByOrderNo(OrderBaleRestRequest orderBaleRestRequest) {
		OrderBaleInfoResponse orderBaleInfoResponse = new OrderBaleInfoResponse();

		OrderBaleDelivery orderBaleDelivery = new OrderBaleDelivery();
		if (StringUtils.isNotEmpty(orderBaleRestRequest.getOrderNo())) {
			Order order = orderMapper.queryByParentOrderNo(orderBaleRestRequest.getOrderNo());
			if (order != null) {
				orderBaleDelivery.setOrderNo(order.getOrderNo());
				getOrderDeliverInfo(orderBaleInfoResponse, orderBaleDelivery);
			}
		} else if (StringUtils.isNotEmpty(orderBaleRestRequest.getLogisticsNo())) {
			orderBaleDelivery.setExpressNo(orderBaleRestRequest.getLogisticsNo());
			getOrderDeliverInfo(orderBaleInfoResponse, orderBaleDelivery);
		} else if (StringUtils.isNotEmpty(orderBaleRestRequest.getRestLogisticsNo())) {
			orderBaleDelivery.setExpressNo(orderBaleRestRequest.getRestLogisticsNo());
			getOrderDeliverInfo(orderBaleInfoResponse, orderBaleDelivery);
		}

		// 查询收货地址
		if (StringUtils.isNotEmpty(orderBaleInfoResponse.getOrderNo())) {
			OrderBaleInfoResponse response = orderDeliverMapper.queryByOrderNo(orderBaleInfoResponse.getOrderNo());
			if (response != null) {
				orderBaleInfoResponse.setReceiverProvinceName(response.getReceiverProvinceName());
				orderBaleInfoResponse.setReceiverCityName(response.getReceiverCityName());
				orderBaleInfoResponse.setReceiverRegionName(response.getReceiverRegionName());
				orderBaleInfoResponse.setReceiverName(response.getReceiverName());
				orderBaleInfoResponse.setReceiverPhone(response.getReceiverPhone());
				orderBaleInfoResponse.setReceiverAddress(response.getReceiverAddress());
			}
		}
		return orderBaleInfoResponse;
	}

	/**
	 * 合单
	 * @param obr
	 * @return
	 */
	@Override
	public long merge(OrderBaleRequest obr) {
		String mergeParams = obr.getMergeOrderParams().toString();
		if(StringUtils.isEmpty(mergeParams)){
			throw new AppRuntimeException("9999","合单参数不能为空！");
		}
		JSONObject json = JSONObject.fromObject(mergeParams);
		Object orders = json.get("orders");
		Object distributorId = json.get("distributorId");
		Object expressNo = json.get("expressNo");
		Object distributorName = json.get("distributorName");
		JSONArray jsonArray = JSONArray.parseArray(orders.toString());
		if(orders==null){
			throw new AppRuntimeException("9999","合并的订单数据不能为空！");
		}
		List<OrderDeliverQueryPage> orderDeliverQueryPages = jsonArray.toJavaList(OrderDeliverQueryPage.class);
		String baleNo =IDUtils.GenerateBillNo("B");
		//生成物流信息
		orderBaleMapper.insert(new OrderBale(){{
			setBaleNo(baleNo);
			setDeleteFlag(0);
			setDistributorId(Long.valueOf(distributorId.toString()));
			setDistributorName(distributorName.toString());
			setReceiverName(orderDeliverQueryPages.get(0).getReceiverName());
			setReceiverAddress(orderDeliverQueryPages.get(0).getReceiverProvinceName()+orderDeliverQueryPages.get(0).getReceiverCityName()+orderDeliverQueryPages.get(0).getReceiverRegionName()+orderDeliverQueryPages.get(0).getReceiverAddress());
			setCreateTime(new Date());
			setOrderStatus(4);
			setDeptId(obr.getAdminOperate().getDeptId());
			setExpressNo(expressNo.toString());
			setDistributorId(Long.valueOf(distributorId.toString()));
			setReceiverPhone(orderDeliverQueryPages.get(0).getReceiverPhone());
			setReceiverProvinceId(orderDeliverQueryPages.get(0).getReceiverProvinceId());
			setReceiverCityId(orderDeliverQueryPages.get(0).getReceiverCityId());
			setDeliverNo(IDUtils.GenerateBillNo("D"));
		}});

		if(CollectionUtil.isNotEmpty(orderDeliverQueryPages)){
			for (OrderDeliverQueryPage orderDeliverQueryPage : orderDeliverQueryPages) {
				OrderDeliver deliver = new OrderDeliver();
				deliver.setOrderStatus(4);
				deliver.setId(orderDeliverQueryPage.getId());
				orderDeliverMapper.update(deliver);
				//创建包裹详细信息
				OrderBaleDetail baleDetail = new OrderBaleDetail();
				baleDetail.setOrderNo(orderDeliverQueryPage.getOrderNo());
				baleDetail.setBaleNo(baleNo);
				baleDetail.setDeleteFlag(0);
				baleDetail.setDeptId(obr.getAdminOperate().getDeptId());
				orderBaleDetailMapper.insert(baleDetail);
			}
		}
		for (OrderDeliverQueryPage orderDeliverQueryPage:orderDeliverQueryPages){
			orderMapper.coupUpdateOrderStatus(orderDeliverQueryPage.getOrderNo());
			Order orderQ = new Order();
			orderQ.setOrderNo(orderDeliverQueryPage.getOrderNo());
			List<Order> orderList = orderMapper.query(orderQ);
			if (null != orderList && !orderList.isEmpty()) {
				orderMapper.coupUpdateParentOrderStatus(orderList.get(0).getParentOrderNo());
			}
			//默认插入一条物流信息
			OrderBaleDelivery orderBaleDelivery = new OrderBaleDelivery();
			orderBaleDelivery.setExpressNo(expressNo.toString());
			orderBaleDelivery.setOrderNo(orderDeliverQueryPage.getOrderNo());
			orderBaleDelivery.setDeliveryCompanyId(Long.valueOf(distributorId.toString()));
			//物流备注暂时写死
			orderBaleDelivery.setRemark("【北京市】 快件已在 【北京太阳宫】 签收, 签收人: 前台, 如有疑问请电联:13370150897 / 010-67443169, 您的快递已经妥投。风里来雨里去, 只为客官您满意。上有老下有小, 赏个好评好不好？【请在评价快递员处帮忙点亮五颗星星哦~】");
			orderBaleDeliveryService.insert(orderBaleDelivery);
		}

		return 0;
	}

	/**
	 * description: 抽取getDeliveryByOrderNo重复代码
	 *
	 * @author: jackHe
	 * @time: 2020/7/30 19:49
	 */
	private void getOrderDeliverInfo(OrderBaleInfoResponse orderBaleInfoResponse, OrderBaleDelivery orderBaleDelivery) {
		List<OrderBaleDelivery> orderBaleDeliveryList = orderBaleDeliveryMapper.query(orderBaleDelivery);
		//转换相应返回实体数据
		List<OrderBaleDeliveryResponse> orderBaleDeliveryResponseList = orderBaleDeliveryList.stream().map(temp -> {
			OrderBaleDeliveryResponse orderAfterSaleTimeResponse = new OrderBaleDeliveryResponse();
			BeanUtils.copyProperties(temp, orderAfterSaleTimeResponse);
			return orderAfterSaleTimeResponse;
		}).collect(Collectors.toList());
		orderBaleInfoResponse.setOrderBaleDeliveryResponseList(orderBaleDeliveryResponseList);
		if (CollectionUtils.isNotEmpty(orderBaleDeliveryList)) {
			orderBaleInfoResponse.setDistributorName(orderBaleDeliveryList.get(0).getDeliveryCompanyName());
			orderBaleInfoResponse.setExpressNo(orderBaleDeliveryList.get(0).getExpressNo());
			orderBaleInfoResponse.setOrderNo(orderBaleDeliveryList.get(0).getOrderNo());
			orderBaleInfoResponse.setDistributorLogo(orderBaleDeliveryList.get(0).getLogisticsCompanyLogo());
		}
	}
}
